package com.open.party.cloud.view.task

import android.Manifest
import android.annotation.SuppressLint
import android.app.Activity
import android.app.AlertDialog
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Bundle
import android.os.Environment
import android.text.TextUtils
import android.view.View
import androidx.core.app.ActivityCompat
import androidx.recyclerview.widget.GridLayoutManager
import cn.android.x.model.data.ResultInfo
import cn.android.x.parent.AppEventBusTitleBaseActivity
import cn.android.x.plugins.webView.WebViewForFilePreviewActivity
import com.jiangyy.easydialog.CommonDialog
import com.open.party.cloud.R
import com.open.party.cloud.ServerConfig
import com.open.party.cloud.model.FileEntity
import com.open.party.cloud.model.data.Api
import com.open.party.cloud.model.data.CodeValue
import com.open.party.cloud.model.task.TaskRateEntity
import com.open.party.cloud.model.task.TaskRateFileBean
import com.open.party.cloud.view.comm.utils.AlbumUtils
import com.open.party.cloud.view.comm.utils.FileChooseUtil
import com.open.party.cloud.view.freePhoto.adpater.ImageSelectedShowAdapter
import com.open.party.cloud.viewModel.FileViewModel
import com.open.party.cloud.viewModel.TaskViewModel
import com.sinothk.android.utils.XUtils
import com.sinothk.helper.image.compress.ImageCompress
import com.sinothk.image.selected.ImgSelectEntity
import com.sinothk.image.selector.PhotoPickerActivity
import com.sinothk.image.selector.SelectModel
import com.sinothk.image.selector.intent.PhotoPickerIntent
import com.sinothk.rxretrofit.RxRetrofit
import com.sinothk.rxretrofit.param.RetrofitParam
import kotlinx.android.synthetic.main.activity_report_rate.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import rx.Subscriber
import rx.android.schedulers.AndroidSchedulers
import rx.schedulers.Schedulers
import java.io.File
import java.util.*
import kotlin.collections.ArrayList

/**
 * 汇报进度
 */
class ReportRateActivity : AppEventBusTitleBaseActivity() {

    private val REQUEST_CODE_PERMISSIONS_CAMERA = 183
    private val REQUEST_CHOOSE_FILE = 83
    private var id: String = ""
    private var photoName: String = ""

    // 文件路径
    private var filePath: String = ""
    private var fileId: String = ""
    private var fileBean: TaskRateFileBean? = null

    //
    var viewModel: TaskViewModel? = null

    private var commPresenter: FileViewModel? = null
    private var appImageSelectedShowAdapter: ImageSelectedShowAdapter? = null //AppImageSelectedShowAdapter

    private var imgSelectList: ArrayList<ImgSelectEntity> = ArrayList()
//    private var isRate: Boolean = false

    override fun getLayoutResId(): Int = R.layout.activity_report_rate

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        setViewTitle("汇报进度", "上传") {
            submit()
        }

        init()
        initListener()
    }

    @SuppressLint("SetTextI18n")
    private fun init() {
        id = intent.getStringExtra("id") as String
//        val isFinish = intent.getBooleanExtra("isFinish", false)
//        if (isFinish) {
//            rateEt.setText("100")
//        }
        viewModel = TaskViewModel()
        commPresenter = FileViewModel()

        appImageSelectedShowAdapter = ImageSelectedShowAdapter(this, Int.MAX_VALUE)
        recyclerView.layoutManager = GridLayoutManager(this, 4)
        recyclerView.setHasFixedSize(true)
        recyclerView.adapter = appImageSelectedShowAdapter
    }

    private fun initListener() {
        uploadFileBtn.setOnClickListener {
            openFIleSys()
        }

        appImageSelectedShowAdapter!!.setOnItemClickListener { _, position ->
            if (imgSelectList.size == position) {
                selectPhoto()
            } else {
                val item: ImgSelectEntity = imgSelectList[position]
                WebViewForFilePreviewActivity.start(this@ReportRateActivity, item.filePath, ServerConfig.getFilePreviewUrl(item.url))
                //图片展示界面
//                val imgList: ArrayList<String> = ArrayList()
//                for (imgEntity: FileEntity in imgSelectList) {
//                    imgList.add(imgEntity.filePath)
//                }
//                PhotoPreviewActivity.start(this@FileUploadCommActivity, position, imgList)
            }
        }

        appImageSelectedShowAdapter!!.setItemDelClick { position ->
            dialogImg(position)
        }

        delBtn.setOnClickListener { dialogDelFile() }
        uploadFileTv.setOnClickListener {
            if (fileBean == null) {
                return@setOnClickListener
            }
            WebViewForFilePreviewActivity.start(this@ReportRateActivity, fileBean!!.fileName, ServerConfig.getFilePreviewUrl(fileBean!!.filePath))
        }
    }

    /**
     * 选择文件
     */
    private fun openFIleSys() {
        if (Environment.getExternalStorageState() != Environment.MEDIA_MOUNTED) {
            return
        }

        val intent = Intent(Intent.ACTION_GET_CONTENT)
        intent.type = "*/*"//设置类型，我这里是任意类型，任意后缀的可以这样写。
        intent.addCategory(Intent.CATEGORY_OPENABLE)
        startActivityForResult(intent, REQUEST_CHOOSE_FILE)
    }

    private fun selectPhoto() {
//        val valueList = ArrayList<String>()
//        valueList.add("拍照")
//        valueList.add("从手机相册选择")
//
//        SingleChoiceDialog.Builder(this)
//            .addList(valueList)
//            .setOnItemClickListener { _: String, pos: Int ->
//
//                when (pos) {
//                    0 -> {
//                        checkCameraPermission()
//                    }
//                    1 -> {
//                        AlbumUtils.openAlbum(this@ReportRateActivity, AlbumUtils.NORMAL)
//                    }
//                }
//
//            }.show()

        gotoSelectImg(this@ReportRateActivity, CodeValue.IMG_SELECT_CODE, SelectModel.SINGLE, true)
    }

    fun gotoSelectImg(activity: Activity, rCode: Int, selectMode: SelectModel, needCamera: Boolean) {
        val intent = PhotoPickerIntent(activity)
        intent.setSelectModel(selectMode)//  SelectModel.SINGLE
        intent.setShowCamera(needCamera, this.application.packageName) // 是否显示拍照， 默认false com.sinothk.living
        startActivityForResult(intent, rCode)
    }

    /**
     * 检查相机权限
     */
    private fun checkCameraPermission() {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
            photoName = XUtils.date().getDateStrByDate(Date(), "yyyyMMddHHmmss")
            AlbumUtils.openCamera(this@ReportRateActivity, AlbumUtils.NORMAL, photoName)
        } else {
            if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA)) {
                val builder = AlertDialog.Builder(this)
                builder.setTitle(R.string.tip_title)
                builder.setMessage(R.string.permission_tip_camera)
                builder.setPositiveButton(R.string.tip_sure) { _, _ ->
                    // 请求用户授权
                    ActivityCompat.requestPermissions(this@ReportRateActivity, arrayOf(Manifest.permission.CAMERA), REQUEST_CODE_PERMISSIONS_CAMERA)
                }
                builder.show()
            } else {
                ActivityCompat.requestPermissions(this@ReportRateActivity, arrayOf(Manifest.permission.CAMERA), REQUEST_CODE_PERMISSIONS_CAMERA)
            }
        }
    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        when (requestCode) {
//            AlbumUtils.OPEN_ALBUM -> {
//                if (data != null && resultCode == RESULT_OK) {
//                    val imgFilePath = AlbumUtils.getDirFromAlbumUri(this@ReportRateActivity, data.data)
//                    if (XUtils.string().isEmpty(imgFilePath)) {
//                        XUtils.toast().show("文件不可用,请尝试重新选择")
//                    } else {
//                        upLoad(bizId, bizType, imgFilePath, bizTypeImage)
//                    }
////                    val fileEntity = FileEntity()
////                    fileEntity.filePath = imgFilePath
////                    imgSelectList.add(fileEntity)
////                    appImageSelectedShowAdapter!!.setData(imgSelectList)
//                }
//            }
//            AlbumUtils.OPEN_CAMERA -> {
//                val externalStorageDirectory = Environment.getExternalStorageDirectory()
//                val file = File(externalStorageDirectory, "$photoName.png")
////
////                val fileEntity = FileEntity()
////                fileEntity.filePath = file.path
//////                imgSelectList.add(fileEntity)
////                appImageSelectedShowAdapter!!.setData(imgSelectList)
//
//                if (XUtils.string().isEmpty(file.path) || File(file.path).length() == 0L) {
//                    XUtils.toast().show("文件不可用,请尝试重新选择")
//                } else {
//                    upLoad(bizId, bizType, file.path, bizTypeImage)
//                }
//
//            }

            CodeValue.IMG_SELECT_CODE -> {
                if (data == null) {
                    return
                }
                val filePathList = data!!.getStringArrayListExtra(PhotoPickerActivity.EXTRA_RESULT)

                if (filePathList != null && filePathList.size > 0) {
                    val imageFilePath = filePathList[0]
//                    hasImage = true
                    val oldFile = File(imageFilePath)
                    val fileSize = oldFile.length()

                    val mb = 0.5 * 1024 * 1024
                    if (fileSize > mb) {// 大于0.5MB压缩
                        ImageCompress.execute(imageFilePath) { obj, _ ->
                            if (obj != null) {

                                val newPath: String = obj as String
                                val newFile = File(newPath)
                                if (newFile.length() > 0) {
                                    upLoad(bizId, bizType, newPath, bizTypeImage)
                                } else {
                                    XUtils.toast().show("压缩图片为空")
                                }
                            } else {
                                XUtils.toast().show("图片压缩失败")
                            }
                        }
                    } else {
                        if (oldFile.length() > 0) {
//                            upLoad(imageFilePath, oldFile.name)
                            upLoad(bizId, bizType, imageFilePath, bizTypeImage)
                        } else {
                            XUtils.toast().show("选择的文件太小")
                        }
                    }
                } else {
                    tip("选择图片失败")
                }
            }

            REQUEST_CHOOSE_FILE -> {
                if (data != null) {
                    filePath = FileChooseUtil.getInstance(this).getChooseFileResultPath(data.data)
                    if (XUtils.string().isEmpty(filePath)) {
                        XUtils.toast().show("文件不可用,请尝试重新选择")
                    } else {
//                        uploadFileTv.text = filePath
                        upLoad(bizId, bizType, filePath, bizTypeFile)
                    }
                }
            }
        }

    }


    private fun submit() {
        uploadRate()
    }

    private fun uploadRate() {

//        val rate = rateEt.text.toString()
        val rateDesc = rateDescEt.text.toString()
//        val desc = descEt.text.toString()
//        if (TextUtils.isEmpty(rate)) {
//            XUtils.toast().show("请输入进度百分比")
//            return
//        }
//        if (rate.toInt() > 100) {
//            XUtils.toast().show("进度最大值为100")
//            return
//        }
        if (TextUtils.isEmpty(rateDesc)) {
            XUtils.toast().show("请输入进度描述")
            return
        }
//        if (TextUtils.isEmpty(desc)) {
//            XUtils.toast().show("请输入详情说明")
//            return
//        }

//        taskRateVo.rate = rate.toInt()
        taskRateVo.description = rateDesc
//        taskRateVo.explain = desc
        taskRateVo.taskId = id
        taskRateVo.endTime = XUtils.date().getDateStrByDate(XUtils.date().curTimeDate, "yyyy-MM-dd HH:mm:ss")

//        fileNetList?.clear()

//        if (!TextUtils.isEmpty(filePath)) {
//            imgSelectList.add(FileEntity(filePath))
//        }

        // 文件处理
        if (fileBean != null || imgSelectList.size > 0) {
            taskRateVo.fileList = ArrayList()

            if (fileBean != null) {
                taskRateVo.fileList.add(fileBean)
            }

            if (imgSelectList.size > 0) {
                for (item in imgSelectList) {
                    taskRateVo.fileList.add(TaskRateFileBean(item.filePath, item.url))
                }
            }
        }

        showLoadingDialog("正在提交")
        viewModel!!.uploadTaskRate(taskRateVo)

//        if (imgSelectList.size > 0) {
////            for (index in imgSelectList.indices) {
//////                if (!TextUtils.isEmpty(imgSelectList[index].filePath)) {
//////                    commPresenter!!.uploadFileForMany(id, Biz.PARTY_TASK_DATA, index.toString(), File(imgSelectList[index].filePath))
//////                }
//////            }
//        } else {
//            // 没有文件直接上传
////
//        }
    }

    private val taskRateVo = TaskRateEntity()

//    private var fileNetList: ArrayList<TaskRateFileBean>? = ArrayList()

//    @Subscribe(threadMode = ThreadMode.MAIN)
//    public fun eventBusFileCallback(result: ResultInfo<FileEntity>) {
//
//        if ("uploadFileForMany" != result.eventType) {
//            return
//        }
//
//        when (result.code) {
//            ResultInfo.SUCCESS -> {
//                val fileBean = result.data
//                fileNetList!!.add(TaskRateFileBean(fileBean.submittedFileName, fileBean.url))
//            }
//            ResultInfo.TOKEN_OVERDUE -> {
//            }
//            else -> {
//            }
//        }
//
//        if (imgSelectList.size - 1 == result.msg.toInt()) {
//            if (fileNetList!!.size > 0) {
//                taskRateVo.fileList = fileNetList
//            }
//            viewModel!!.uploadTaskRate(taskRateVo)
//        }
//    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public fun eventBusCallback(result: ResultInfo<TaskRateEntity>) {

        if ("uploadTaskRate" != result.eventType) {
            return
        }

        hideLoadingDialog()

        when (result.code) {
            ResultInfo.SUCCESS -> {
                val taskRateEntity = result.data as TaskRateEntity

                EventBus.getDefault().post(taskRateEntity)

                XUtils.toast().show("上传成功")
                finish()
            }
            ResultInfo.TOKEN_OVERDUE -> {
            }
            else -> {
                XUtils.toast().show(result.msg)
            }
        }
    }

    // ========================================================================
    private var bizId = ""
    private var bizType = "ReportRate"
    private var bizTypeFile = "bizTypeFile"
    private var bizTypeImage = "bizTypeImage"

    private fun upLoad(bId: String, bizType: String, newPath: String, fromWhere: String) {

        // 传单文件文件和键值对
        RxRetrofit.init(ServerConfig.SERVER_URL, ServerConfig.getHeader()).create(Api::class.java)
            .uploadFile(bId, bizType, "", RetrofitParam.createFileParam("file", File(newPath)))
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : Subscriber<ResultInfo<FileEntity>>() {

                override fun onStart() {
                    showLoadingDialog("正在上传")
                }

                override fun onNext(result: ResultInfo<FileEntity>?) {
                    if (result != null) {
                        if (result.code == 0) {
                            if (result.data != null) {
                                bizId = result.data.bizId

                                if ("bizTypeFile" == fromWhere) {
                                    val fileName = XUtils.string().getNotNullValue(result.data.submittedFileName, result.data.fileName)
                                    uploadFileTv.text = fileName
                                    fileId = result.data.id

                                    fileBean = TaskRateFileBean(fileName, result.data.url)

                                    fileView.visibility = View.VISIBLE
                                } else {
                                    val fileName = XUtils.string().getNotNullValue(result.data.submittedFileName, result.data.fileName)

                                    val imgSelectEntity: ImgSelectEntity? = ImgSelectEntity()
                                    imgSelectEntity!!.id = result.data.id.toString()
                                    imgSelectEntity.filePath = fileName
                                    imgSelectEntity.url = result.data.url

                                    imgSelectList.add(imgSelectEntity)
                                    refreshImgView()
                                }
                                return
                            } else {
                                XUtils.toast().show("无文件信息")
                            }
                        } else {
                            XUtils.toast().show(result.msg)
                        }
                    } else {
                        XUtils.toast().show("提交失败")
                    }
                }

                override fun onCompleted() {
                    hideLoadingDialog()
                }

                override fun onError(e: Throwable?) {
                    hideLoadingDialog()
                    if (e != null) {
                        XUtils.toast().show("文件上传失败")
                    }
                }
            })
    }

    private fun refreshImgView() {
        appImageSelectedShowAdapter?.setData(imgSelectList)
    }

    private fun delFileById(fileId: String, fromWhere: String) {
        if (XUtils.string().isEmpty(fileId)) {
            return
        }

        val ids: Array<String> = arrayOf(fileId)

        // 传单文件文件和键值对
        RxRetrofit.init(ServerConfig.SERVER_URL, ServerConfig.getHeader()).create(Api::class.java)
            .delFileById(ids)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : Subscriber<ResultInfo<Boolean>>() {

                override fun onStart() {
                    super.onStart()
                    showLoadingDialog("正在删除")
                }

                override fun onNext(result: ResultInfo<Boolean>?) {

                    hideLoadingDialog()

                    if (result != null) {
                        if (result.code == 0) {
                            if (result.data != null && result.data) {
                                if ("bizTypeFile" == fromWhere) {
                                    delFileSuccess()
                                } else {
                                    delImgSuccess()
                                }
                                return
                            } else {
                                XUtils.toast().show(result.msg)
                            }
                        } else {
                            XUtils.toast().show(result.msg)
                        }
                    } else {
                        XUtils.toast().show("删除失败")
                    }
                }

                override fun onCompleted() {
                }

                override fun onError(e: Throwable?) {
                    hideLoadingDialog()
                    if (e != null) {
                        XUtils.toast().show("文件删除失败")
                    }
                }
            })
    }

    private fun delFileSuccess() {
        fileView.visibility = View.GONE
    }

    private fun dialogDelFile() {
        CommonDialog.Builder(this)
            .setTitle("提示")
            .setMessage("确认移除已添加的文件吗？")
            .setPositiveButton("确认") {
                if (appImageSelectedShowAdapter!!.itemCount > 0) {
                    // 删除服务器文件
                    delFileById(fileId, bizTypeImage)
                }
            }.setNegativeButton("取消") {

            }.show()
    }

    // ====================================
    fun delImgSuccess() {
        // 移除展示数据
        imgSelectList.removeAt(delPosition)
        // 刷新界面
        appImageSelectedShowAdapter?.setData(imgSelectList)
        appImageSelectedShowAdapter?.notifyDataSetChanged()
    }

    private var delPosition: Int = 0
    private fun dialogImg(position: Int) {
        CommonDialog.Builder(this)
            .setTitle("提示")
            .setMessage("确认移除已添加的图片吗？")
            .setPositiveButton("确认") {
                if (appImageSelectedShowAdapter!!.itemCount > 0) {
                    delPosition = position
                    // 删除服务器文件
                    delFileById(imgSelectList[position].id, bizTypeImage)
                }
            }.setNegativeButton("取消") {

            }.show()
    }
}